var element;
var functionTreeData;
let uuid = 0;

$(document).ready(function () {

    UserInfo.init(() => top.location.href = 'login');

    let src_path = !UserInfo.fileId || UserInfo.fileId == 0 ? '/images/bg_image/boy.jpg' : '/file/view/' + UserInfo.fileId;
    let str = '<img src="' + src_path + '" class="layui-nav-img">' + `${UserInfo.orgName ? UserInfo.orgName + ' - ' : ''}${UserInfo.userName}`;
    $("#username").html(str);

    if (UserInfo.postList && UserInfo.postList.length > 1) {
        var postMenu = '<dl class="layui-nav-child postMenu">';

        for (var i = 0; i < UserInfo.postList.length; i++) {
            postMenu = postMenu + `<dd><a href="javascript:changePost([${UserInfo.postList[i].orgId},${UserInfo.postList[i].postId}]);">${UserInfo.postList[i].name}</a></dd>`;
        }

        postMenu = postMenu + '</dl>';

        $('#postname').after(postMenu);
    }

    //1)选择的岗位和角色
    changePost(UserInfo.postList.length == 0 ? [0, 0] : [UserInfo.postList[0].orgId, UserInfo.postList[0].postId]);
});

$(".new_nav .s_nav").hover(function () {
    $(this).children(".s_nav_pull").removeClass("layui-hide");
}, function () {
    $(this).children(".s_nav_pull").addClass("layui-hide");
});

//修改密码
function update_pwd() {
    loading = layer.open({
        type: 1,
        shade: false,
        title: "修改密码",
        area: ['420px'], //宽高
        content: $('.update_pwd'),
        cancel: function () {
            //关闭窗口执行的操作
        }
    });
}

//退出登录
function to_login() {
    $.post('/logout');
    top.location.href = 'login';
}

$("#update_pwd").click(function () {
    var password = $("#password").val();
    var newPwd = $("#newPwd").val();
    var isPwd = $("#isPwd").val();
    if (password === "") {
        $("#password").focus();
        layer.tips('原始密码不能为空', '#password');
    } else if (newPwd === "") {
        $("#newPwd").focus();
        layer.tips('新密码不能为空', '#newPwd');
    } else if (isPwd === "") {
        $("#isPwd").focus();
        layer.tips('请再次确认密码', '#isPwd');
    } else if (newPwd !== isPwd) {
        layer.msg("两次输入的密码不一致");
    } else {
        $.ajax({
            url: 'http://localhost:8089/sysUser!changePassword.do',
            type: 'post',
            data: {
                'sysUser.loginName': password,
                'sysUser.userLoginpwd': newPwd
            },
            success: function (res) {
                if (res.OK === "OK") {
                    layer.msg("修改成功");
                    layer.close(loading);
                } else {
                    layer.msg(res.msg);
                }
            }
        });

    }
});

function closeMe(ele) {
    if ($(ele).parent().hasClass("layui-nav-itemed")) {
        setTimeout(function () {
            $(ele).parent().removeClass("layui-nav-itemed")
        }, 10)
    }
}

function changePost(ids) {
    $('.layui-nav-tree').html('');
    $('#postname').html('');

    // 1)显示岗位名称
    for (var i = 0; i < UserInfo.postList.length; i++) {
        if (UserInfo.postList[i].orgId == ids[0] && UserInfo.postList[i].postId == ids[1]) {
            $('#postname').html(`${UserInfo.postList[i].name}`);
            break;
        }
    }

    // 2)选择的岗位和所有角色取得菜单
    $.ajax({
        url: `${'/privilege/function/functionTreeList'}`,
        type: 'post',
        dataType: "json",
        data: {ids: JSON.stringify(ids)},
        async: false,
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        timeout: 6000,//超时时间设置为1分钟；
        error: function () {
        },
        success: function (res) {
            let rl = res.List;

            // 3）数据格式化
            functionTreeData = formatMenuData(rl, 'parentId', 'id', 'functionName', 'functionUrl', 'functionIcon');
            sessionStorage.setItem("erp_funcObjTree", JSON.stringify(functionTreeData))

            // 4）显示菜单
            uuid = 0;
            var nodeContent = drawnode(functionTreeData, 0);
            if (nodeContent) {
                $('.layui-nav-tree').append(nodeContent);
            }

            layui.use('element', function () {
                var ele = layui.element;
                ele.render('nav');
            });
        }.bind(this)
    });
}


/**
 * 编辑菜单内容
 * @param data  数据
 * @param level 显示层级
 */
function drawnode(data, level) {
    var contents = ['<li class="layui-nav-item %s"><a %s>%s</a><dl class="layui-nav-child">%s</dl></li>',
        '<li class="layui-nav-item"><a>%s</a></li>',
        '<dd class="%s"><a lay-href="%s">%s</a></dd>'
    ];
    var result = '';
    var childNode;


    if (data.length > 0) {
        for (var i = 0; i < data.length; i++) {
            if (data[i].list && data[i].list.length > 0) {
                result += contents[0].replace(/%s/, "menu-level-" + data[i].menuLevel).replace(/%s/, data[i].href == "#" ? "" : "lay-href=\"" + data[i].href + "\"").replace(/%s/, data[i].name).replace(/%s/, drawnode(data[i].list, 1));
            } else {
                if (level == 0) {
                    result += contents[1].replace(/%s/, data[i].name);
                } else {
                    result += contents[2].replace(/%s/, "menu-level-" + data[i].menuLevel).replace(/%s/, data[i].href).replace(/%s/, data[i].name);
                }
            }
        }
    }

    return result;
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 */
function formatMenuData(values, pid, id, name, href, icon) {
    var tree = [],
        item;

    var map = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.length; i++) {
        item = new Object();

        item.name = values[i][name];
        item.value = values[i][id];
        item.href = values[i][href];
        item.functionIcon = values[i][icon];
        item.list = [];

        map.set(values[i][id], item);
    }

    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.length; i++) {
        var subObj = map.get(values[i][id])
        if (values[i][pid] > 0) {
            var obj = map.get(values[i][pid]);
            obj.list.push(subObj);
        } else {
            subObj.menuLevel = 1
            tree.push(subObj);
        }
    }

    // 3)删除没有子项目的list
    for (var i = 0; i < values.length; i++) {
        var obj = map.get(values[i][id]);
        if (obj.list.length == 0) {
            delete obj.list;
        }
    }

    // 4)加上 menuLevel 属性
    tree.forEach(function (itree) {
        setMenuLevel(itree)
    })

    return tree;
}

/*
* 给树节点，加上 menuLevel 属性
* */
function setMenuLevel(objMenu) {
    if (objMenu.hasOwnProperty("list")) {
        objMenu.list.forEach(function (imenu) {
            imenu.menuLevel = objMenu.menuLevel + 1
            if (imenu.hasOwnProperty("list")) setMenuLevel(imenu)
        })
    }
}
